import axios from 'axios'
import { Message, Spin } from 'view-design'
import Cookies from 'js-cookie'
import { router } from '../router/index'
import { buildSign } from './signUtils'
import { getStore, setStore } from './storage'

// 统一请求路径前缀
const base = '/sports/manager'
// 超时设定

const navMap = {
  'campus-operate': 0,
  'platform-manager': 1,
  'crm-system': 2
}

axios.defaults.timeout = 20000
axios.defaults.baseURL = process.env.VUE_APP_BASE_URL
axios.interceptors.request.use((config) => {
  const accessToken = getStore('accessToken')
  const tenantId = getStore('x-tenant-header')
  const userId = getStore('userId')
  const accountId = getStore('accountId')
  const nickname = getStore('nickname')
  config.headers = {
    ...config.headers,
    'x-token-header': accessToken,
    'x-tenant-header': tenantId || '0',
    'x-user-header': userId || '0',
    'x-client-header': 'admin',
    'x-account-header': accountId || '0',
    'x-timestamps': new Date().getTime(),
    'x-nav-type': navMap[sessionStorage.getItem('currNav') || 'campus-operate'],
    'x-user-nickname': encodeURI(nickname)
  }

  config.headers['x-sign-header'] = buildSign(config)

  return config
}, (err) => {
  Message.error('请求超时')
  return Promise.resolve(err)
})

// http response 拦截器
axios.interceptors.response.use((response) => {
  // 拦截请求头用于下载文件获取后端返回的文件名字
  let filename = response.headers['content-disposition'] && response.headers['content-disposition'].split(';')[1].split('filename=')[1]
  if (filename) {
    if (!filename.includes('%')) {
      filename = decodeURIComponent(escape(filename))
      response.data.filename = filename
    } else {
      filename = decodeURIComponent(filename)
      response.data.filename = filename
    }
  }
  const data = response.data
  // 根据返回的code值来做不同的处理(和后端约定)
  switch (true) {
    case [1010003].includes(data.code):
      // 未登录 清除已登录状态 清除锁屏状态
      Cookies.set('userInfo', '')
      Cookies.set('locking', '0')
      setStore('accessToken', '')
      if (router.history.current.name != 'login') {
        if (data.message !== null) { Message.error(data.message) } else { Message.error('登录失效，请重新登录') }

        router.push('/login')
      }
      break
    case [500, 1010002, 1010004, 1010007, 1010008, 1020000, 12102003, 12102004, 12102002].includes(data.code):
      // 错误
      if (data.message !== null) { Message.error(data.message) } else { Message.error('未知错误') }

      break
    default:
      return data
  }

  return data
}, (err) => {
  // 返回状态码不为200时候的错误处理
  Message.error(err.toString())
  return Promise.resolve(err)
})

export function getRequest (url, params, needBaseUrl = true) {
  return axios({
    method: 'get',
    url: `${needBaseUrl ? base : ''}${url}`,
    params
  })
}

export function postRequest (url, params, needBaseUrl = true, timeout = 20000) {
  return axios({
    method: 'post',
    url: `${needBaseUrl ? base : ''}${url}`,
    data: params,
    transformRequest: [function (data) {
      let ret = ''
      for (const it in data) { ret += `${encodeURIComponent(it)}=${encodeURIComponent(data[it])}&` }

      ret = ret.substring(0, ret.length - 1)
      return ret
    }],
    timeout
  })
}

export function postRequestFile (url, params, needBaseUrl = true, timeout = 20000) {
  return axios({
    method: 'post',
    url: `${needBaseUrl ? base : ''}${url}`,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    timeout
  })
}

export function postRequestJSON (url, params, needBaseUrl = true, timeout = 20000) {
  /* var memberInfo = store.getters.memberInfo;
    let userInfo = JSON.parse(Cookies.get("userInfo"));
    if(memberInfo && memberInfo.endTimeStamp && memberInfo.endTimeStamp<new Date() && memberInfo.endTimeStamp !==-1 && userInfo.type !="2"){
        return Modal.confirm({
            content:`<span style="font-weight: bold;font-size: 18px;">您的机构账号已过期</span>&nbsp;&nbsp;<span style="color: darkgray;font-size:18px;">请及时续费</span>`,
            title:"提醒",
            okText:"续费",
            cancelText:'取消',
            width:'400px',
        });
    } */
  return axios({
    method: 'post',
    url: `${needBaseUrl ? base : ''}${url}`,
    data: params,
    headers: {
      'Content-Type': 'application/json'
    },
    timeout
  })
}

export function putRequestJSON (url, params, needBaseUrl = true) {
  return axios({
    method: 'put',
    url: `${needBaseUrl ? base : ''}${url}`,
    data: params,
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

export function delRequestJSON (url, params, needBaseUrl = true) {
  return axios({
    method: 'delete',
    url: `${needBaseUrl ? base : ''}${url}`,
    data: params,
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

export function putRequest (url, params, needBaseUrl = true) {
  return axios({
    method: 'put',
    url: `${needBaseUrl ? base : ''}${url}`,
    data: params,
    transformRequest: [function (data) {
      let ret = ''
      for (const it in data) { ret += `${encodeURIComponent(it)}=${encodeURIComponent(data[it])}&` }

      ret = ret.substring(0, ret.length - 1)
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

export function postBodyRequest (url, params) {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params
  })
}

/**
 * 无需token验证的GET请求 避免旧token过期导致请求失败
 * @param {*} url
 * @param {*} params
 */
export function getNoAuthRequest (url, params) {
  return axios({
    method: 'get',
    url: `${base}${url}`,
    params
  })
}

export function postNoAuthRequest (url, params) {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    transformRequest: [function (data) {
      let ret = ''
      for (const it in data) { ret += `${encodeURIComponent(it)}=${encodeURIComponent(data[it])}&` }

      ret = ret.substring(0, ret.length - 1)
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

export function postRequestDownloadExcel (url, params, needBaseUrl = true) {
  return axios({
    method: 'POST',
    url: `${needBaseUrl ? base : ''}${url}`,
    data: params,
    headers: {
      'Content-Type': 'application/json'
    },
    responseType: 'blob'
  }).then((res) => {
    console.log('res', res)
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    const fileName = res.filename
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  })
}

export function getRequestDownloadExcel (url, params, needBaseUrl = true, filename) {
  console.log('params', params)
  return axios({
    method: 'GET',
    url: `${needBaseUrl ? base : ''}${url}`,
    params,
    headers: {
      'Content-Type': 'application/json'
    },
    responseType: 'blob'
  }).then((res) => {
    Spin.hide()
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    let fileName = filename || res.filename
    fileName = fileName.replaceAll('"', '')
    // 有转义符，先把转义符截取
    // console.log('fileName', fileName)
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    link.setAttribute('download', fileName.trim())
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  })
}
